package com.xyauto.theme.utils

import android.app.WallpaperManager
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.provider.Settings
import com.autochips.metazone.AtcMetazone
import com.blankj.utilcode.util.LogUtils
import com.xyauto.theme.App
import com.xyauto.theme.bean.IThemeBean
import com.xyauto.theme.bean.JMEThemeBean
import org.jetbrains.annotations.NotNull
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream

object JieMainYiManager {

    private const val KEY_PACKAGE_NAME: String = "com.xygala.launcherall"
    private const val KEY_UI_TOTAL: String = "xy.launcher.ui.total"

    /**是否支持多UI*/
    private var supportTheme: Boolean = false

    var themeCount: Int = 0

    private val show_meta_zone = ByteArray(4)

    fun init(@NotNull context: Context) {
        val packageManager = context.packageManager
        AtcMetaZoneTools.readreserved_offset(show_meta_zone, AtcMetaZoneTools.KEY_DISPLAY_THEME_LIST)
        LogUtils.i("ReadAppInfo: huang show_meta_zone=>${show_meta_zone.contentToString()}")
        themeCount = Settings.System.getInt(App.instance.contentResolver, KEY_UI_TOTAL, 0)
        supportTheme = try {
            val info = packageManager.getPackageInfo(KEY_PACKAGE_NAME, PackageManager.GET_ACTIVITIES)
            info != null && themeCount > 0
        } catch (e: PackageManager.NameNotFoundException) {
            LogUtils.e("findJieMainYiTheme.error = ${e.message}")
            false
        }
    }


    fun findTheme(): MutableList<IThemeBean> {
        val arrayList = arrayListOf<IThemeBean>()
        if (supportTheme) {
            AtcMetaZoneTools.readreserved_offset(show_meta_zone, AtcMetaZoneTools.KEY_DISPLAY_THEME_LIST)
            for (i in 0 until themeCount) {
                if (getMetaZoneBit(i).toInt() == 0) {
                    val index = i + 1
                    val preViewRes = getPreViewRes(index)
                    val wallpaperRes = getWallpaperRes(index)
                    if (preViewRes.isEmpty() || wallpaperRes.isEmpty()) continue
                    arrayList.add(JMEThemeBean(i, preViewRes, wallpaperRes))
                }
            }
        }
        return arrayList;
    }

    fun saveSelectData(select: Int) {
        var show_index: Int = select
        var index = 0
        while (index < 8 * show_meta_zone.size) {
            if (getMetaZoneBit(index).toInt() == 0) {
                if (show_index == 0) {
                    break
                }
                show_index--
            }
            index++
        }
        AtcMetaZoneTools.writereserved_offset(index, 0x268, 1,true)
    }

    fun setWallpaper(wp: WallpaperManager, wallpaper: String?) {
        val file = wallpaper?.let { File(wallpaper) } ?: return
        if (file.exists()) {
            var input: InputStream? = null
            try {
                input = FileInputStream(file)
                //使用源码编译不用注销
                //wallpaperManager.setStream(in, null, false, WallpaperManager.FLAG_SYSTEM);
                //wallpaperManager.setStream(in); // 2022.8.11 huang setStream方法无法传递文件较大壁纸 出现机器卡死
                val bitmap = BitmapFactory.decodeStream(input)
                wp.setBitmap(bitmap)
                input.close()
                LogUtils.i("setWallpaper: $wallpaper")
            } catch (e: IOException) {
                LogUtils.e("setWallpaper error: ${e.message}")
            } finally {
                input?.close()
            }
        }
    }

    private fun getPreViewRes(index: Int): String {
        val file = "/system/priv-app/LauncherXYAll/icon_preview_ui$index.png"
        if (File(file).exists()) {
            return file
        }
        return ""
    }

    private fun getWallpaperRes(index: Int): String {
        val file = "/system/priv-app/LauncherXYAll/default_wallpaper$index.png"
        if (File(file).exists()) {
            return file
        }
        return ""
    }


    private fun getMetaZoneBit(position: Int): Byte {
        val pos = position / 8
        val pos_bit = position % 8
        var value = show_meta_zone[pos]
        value = (value.toInt() shr pos_bit and 0x01).toByte()
        return value
    }


}